package com.flyco.modules.stm.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyco.common.api.vo.Result;
import com.flyco.common.aspect.annotation.AutoLog;
import com.flyco.common.system.base.controller.BaseController;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.stm.entity.*;
import com.flyco.modules.stm.model.RetreatContext;
import com.flyco.modules.stm.service.IOaWldbService;
import com.flyco.modules.stm.service.IStmRetreatItemService;
import com.flyco.modules.stm.service.IStmStoreInfoService;
import com.flyco.modules.stm.service.IStmRetreatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 业务和出入库关联表
 * @Author: flyco
 * @Date:   2022-11-29
 * @Version: V1.0
 */
@Slf4j
@Api(tags="退仓管理")
@RestController
@RequestMapping("/f/stm/stmRetreat")
public class StmRetreatController extends BaseController<StmRetreat, IStmRetreatService> {
	@Autowired
	private IStmRetreatService stmRetreatService;
	@Autowired
	private IStmRetreatItemService stmRetreatItemService;
	@Autowired
	private IStmStoreInfoService stmStoreInfoService;
	@Autowired
	private IOaWldbService iOaWldbService;

	/**
	 * 分页列表查询
	 */
	@AutoLog(value = "业务和出入库关联表-分页列表查询")
	@ApiOperation(value="业务和出入库关联表-分页列表查询", notes="业务和出入库关联表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(StmRetreat stmRetreat,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<StmRetreat> queryWrapper = QueryGenerator.initQueryWrapper(stmRetreat, req.getParameterMap());
		Page<StmRetreat> page = new Page<>(pageNo, pageSize);
		queryWrapper.eq("version",2).ne("status",0);
		IPage<StmRetreat> pageList = stmRetreatService.page(page, queryWrapper);
		if (pageList.getTotal() > 0) {
			List<StmStoreInfo> storeInfos = stmStoreInfoService.list();
			Map<Long, String> storeInfoMaps = storeInfos.stream().collect(Collectors.toMap(StmStoreInfo::getStoreId, StmStoreInfo::getName, (key1, key2) -> key2));
			pageList.getRecords().forEach(retreat -> {
				retreat.setStatusDictText();
				if (oConvertUtils.isNotEmpty(retreat.getStoreId())) {
					if (storeInfoMaps.containsKey(retreat.getStoreId())) {
						retreat.setStoreId_dictText(storeInfoMaps.get(retreat.getStoreId()));
					} else {
						if (Objects.equals(0L , retreat.getStoreId() )) {
							retreat.setStoreId_dictText("线上商城");
						}
					}
				}
			});
		}
		return Result.ok(pageList);
	}

	/**
	 * 通过id查询
	 */
	@AutoLog(value = "业务和出入库关联表-通过id查询")
	@ApiOperation(value="业务和出入库关联表-通过id查询", notes="业务和出入库关联表-通过id查询")
	@GetMapping(value = "/listStmRetreatItemByMainId")
	public Result<?> queryPageList(StmRetreatItem stmRetreatItem,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		if(stmRetreatItem.getRetreatId()==null){
			return Result.error("退仓单id不能为空");
		}
		QueryWrapper<StmRetreatItem> queryWrapper = QueryGenerator.initQueryWrapper(stmRetreatItem, req.getParameterMap());
		Page<StmRetreatItem> page = new Page(pageNo, pageSize);
		IPage<StmRetreatItem> pageList = stmRetreatItemService.page(page, queryWrapper);
		if (pageList.getTotal() > 0) {
			pageList.getRecords().forEach(StmRetreatItem::setStockTypeDictText);
		}
		return Result.ok(pageList);
	}

	@AutoLog(value = "推送退仓单到OA表")
	@ApiOperation(value = "推送退仓单到OA表", notes = "推送退仓单到OA表")
	@PostMapping(value = "/push-oa")
	public Result pushOA(@RequestBody OaPushDTO oaPushDTO) {
		if(oaPushDTO.getId()==null){
			return Result.error("退仓单号不能为空");
		}
		//要货单，判断调入工厂和调入库存地点不能为空
		if(StrUtil.isBlank(oaPushDTO.getInOutCode()) || StrUtil.isBlank(oaPushDTO.getInOutAddressCode())){
			return Result.error("参数不能为空");
		}

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		Result<RetreatContext> result = stmRetreatService.pushOABefore(oaPushDTO,sysUser.getRealname());
		if(result.getCode()!=200){
			return result;
		}

		try {
			iOaWldbService.pushRetreatOA(oaPushDTO,result.getResult(),sysUser.getRealname());
		} catch (Exception e) {
			log.error("pushRetreatOA：",e);

			//状态还原
			StmRetreat retreatBack = new StmRetreat();
			retreatBack.setId(oaPushDTO.getId());
			retreatBack.setStatus(1);
			stmRetreatService.updateById(retreatBack);

			return Result.error("推送失败");
		}

		return Result.ok("推送成功");
	}

	@AutoLog(value = "审批退仓单")
	@PostMapping(value = "/apply")
	public Result<?> apply(@RequestBody RetreatApplyDTO retreatApplyDTO) {
		if(retreatApplyDTO.getStatus()==null || retreatApplyDTO.getIds()==null){
			return Result.error("参数不能为空");
		}

		return stmRetreatService.apply(retreatApplyDTO.getStatus(), Arrays.asList(retreatApplyDTO.getIds()));
	}

  /**
   * 导出excel
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, StmRetreat stmRetreat) {
      return super.exportXls(request, stmRetreat, StmRetreat.class, "业务和出入库关联表");
  }

  /**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      return super.importExcel(request, response, StmRetreat.class);
  }

}
